<?php

#<editor-fold defaultstate="collapsed" desc="start">
ini_set('max_execution_time', 30);
include 'core/core.php';
CCore::Using('logger.inline');
$oLogger = null;
#</editor-fold>
//$oLogger = new CCoreLoggerInline('<br />'."\r\n");

$folders = array();
$messages = array();
$message = $top = $messagesIframe = '';

CCore::Using('socket.imap');
CCore::Using('mime.charsets');
CCore::Using('mime.headers');
CCore::Using('mime.message');

$oImapConfig = new CCoreSocketImapConfig('u-server', 143, 'test@localhost', 'p12345', 5, 5);
$oImap = new CCoreSocketImap($oImapConfig, $oLogger);

$oImap->ConnectAndLogin();

$f = isset($_GET['folder']) ? $_GET['folder'] : 'INBOX';

$list = $oImap->ListFolders();
asort($list);
foreach ($list as $item)
{
	if ($f === $item[0])
	{
		$folders[] = '<b><a href="?folder='.urlencode($item[0]).'">'.$item[0].'</a></b><br />';
	}
	else
	{
		$folders[] = '<a href="?folder='.urlencode($item[0]).'">'.$item[0].'</a><br />';
	}
}

$oImap->SelectFolder($f);

$m = isset($_GET['uid']) ? $_GET['uid'] : null;
$im = isset($_GET['_uid']) ? $_GET['_uid'] : null;
if (null !== $im)
{
	$messagesIframe = '<iframe style="border: solid 0px black; ;width: 100%; height: 100%" src="?uid='.$im.'&folder='.urlencode($f).'" />';
}
else if (null === $m)
{
	$fAdd = (null === $f) ? '' : '&folder='.urlencode($f);
	$r = $oImap->Fetch(array(CCoreSocketImapFetch::UID, CCoreSocketImapFetch::BODY.'[HEADER]', CCoreSocketImapFetch::RFC822_SIZE), '1:20', false, true);
	foreach ($r as $l)
	{
		$oMimeCharsets = new CCoreMimeCharsets();
		$oMimeHeaders = new CCoreMimeHeaders($oMimeCharsets, $l[CCoreSocketImapFetch::BODY.'[HEADER]']);
		$oSubjectHeader = $oMimeHeaders->GetByName('subject');
		$sSubject = 'no subject';
		if ($oSubjectHeader)
		{
			$sSubject = $oSubjectHeader->DecodedValue();
		}
		
		$messages[] = $l[CCoreSocketImapFetch::INDEX] .') <a href="?_uid='.$l[CCoreSocketImapFetch::UID].$fAdd.'">'.$sSubject.' ['.$l[CCoreSocketImapFetch::RFC822_SIZE].']</a><br />';
	}
}
else
{
	$r = $oImap->Fetch(array(CCoreSocketImapFetch::BODY.'[]'), $m, true, true);
	if (isset($r[0][CCoreSocketImapFetch::BODY.'[]']))
	{
		$oMime = new CCoreMimeMessage('utf-8', $r[0][CCoreSocketImapFetch::BODY.'[]']);

		$message .= 'FROM: '.htmlspecialchars($oMime->GetFromValue()).'<br />';
		$message .= 'SUBJECT: '.htmlspecialchars($oMime->GetSubjectValue()).'<br />';
		$message .= '<hr />';

		$html = $oMime->GetHtmlText();
		$message .= (empty($html)) ? '<pre>'.$oMime->GetPlainText().'</pre>' : $html;
	}
}

if (null === $m)
{
?>
<div><?php echo $top; ?></div>
<div style="float: left; width: 200px; overflow: hidden"><?php echo implode('', $folders); ?></div>
<div style="margin-left: 200px"><?php echo implode('', $messages).$messagesIframe; ?></div>
<?php
}
else if (strlen($message) > 0)
{
	echo $message;
}